前端自动化测试(二)- 单元测试

上一篇博客我们大概讲解了软件的开发模式,自动化测试的分类和方式,以及对应的一些技术框架介绍和选型,都是些理论性的知识。这一篇我们就先来实战一下前端单元测试。

选型

mocha 大家经常用,写node后端时也经常用,我们就先略过它了。
这次我想研究一下karmajest

  1. karma - Google Angular 团队开发的测试运行平台。它配置简单灵活,能够很方便将测试在多个真实浏览器中运行。它使用 Nodejs 构建,因此跨平台,还支持 PhantomJS 浏览器,还支持多种框架,包括以下介绍的 Jasmine、Qunit 和 Mocha。一次可以在多个浏览器及设备中进行测试,并控制浏览器行为和测试报告。虽然它不支持 Nodejs 的测试,不过没什么影响,因为 Nodejs 并不依赖于浏览器。

  2. jest – facebook 出品的大而全的测试框架,React 官方推荐的单元测试框架,配置简单运行速度快。(备注:无法和 Karma 进行集成)

想研究下这俩的原因是,karma是集各家之大成,集成了很多测试框架和工具,功能齐全。由于我司项目是React,所以也想研究下jest,可惜和karma并不兼容。

说干就干。

karma

打开karma官网,直接一行大字
avatar
感觉作者是写angular的,为angular量身制作的。

官方推荐

When should I use Karma?
You want to test code in real browsers.
You want to test code in multiple browsers (desktop, mobile, tablets, etc.).
You want to execute your tests locally during development.
You want to execute your tests on a continuous integration server.
You want to execute your tests on every save.
You love your terminal.
You don’t want your (testing) life to suck.
You want to use Istanbul to automagically generate coverage reports.
You want to use RequireJS for your source files.

安装

  1. npm install karma –save-dev

  2. npm install karma-jasmine karma-chrome-launcher jasmine-core –save-dev 官方demo是安装jasmine框架,我不太想用,我们还是用熟悉的mocha吧 一会再装

  3. 先 init

  4. npx karma init my.conf.js
    avatar
    可以看到图中,让上下键选择测试框架,它会自己帮我们安装,这里我们选择mocha

  5. 下一步是问你是不是用Require.js,我们选择否

  6. avatar

选择运行浏览器,我们就选Chrome吧,发现还得选一个,什么ChromeHeadless、ChromeCanary、PhantomJS、Firefox、safari、ie什么的,好吧,他是个多选项,让你可以选择多个环境,害。我们就选个Chrome真实环境吧,别的以后再说。

  1. avatar
    让选择test文件的路径或匹配方式,我们输入一个 *.test.js,也就是所有以test.js结尾的,都是我们的测试问文件。但是它好像得先创建一个,如果是test文件夹下的话,也得创建一个能让它找到。

  2. avatar
    没看懂,输入空格跳过

  3. avatar
    是否在文件变动时,执行测试,咱们还是算了吧,手动执行吧,用不着这么高级的功能。

  4. avatar
    终于成功了,这一顿配置

avatar
并且我发现,package.json也被贴心的更改了,我们直接 npm i

  1. 再装个配套的可以在浏览器运行的断言库

    npm install chai karma-chai –save-dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// 生成的配置文件my.conf.js
module.exports = function (config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: "",
// 测试框架
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ["mocha", "chai"],
// 测试入口文件
// list of files / patterns to load in the browser
files: ["*.test.js"],

// list of files / patterns to exclude
exclude: [],
// 预处理器 karma-webpack
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {},
// 测试报告
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ["progress"],

// web server port
port: 9876,

// enable / disable colors in the output (reporters and logs)
colors: true,

// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,

// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// 浏览器
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ["Chrome"],

// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,

// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
});
};

开整

  1. 执行 npx karma start my.conf.js

报错缺 mocha库,装一下子。
avatar
终于起来了,还起来了个Chrome浏览器,还聚焦切屏了。
avatar

  1. demo一个,mocha的用法我就不在这介绍了。
1
2
3
4
5
6
describe("demo", () => {
it("first test", () => {
throw new Error('123123');
});

});

avatar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// demo.js
function demo(arg1, arg2, arg3) {
return arg1 + arg2 + arg3;
}

export { demo };

// demo.test.js
import { assert } from "chai";

import { demo } from "./demo";

describe("demo", () => {
it("first test", () => {
const result = demo(1, 2, 3);
assert.equal(result, 6);
});

it("second test", () => {
const result = demo(1, 2, 3);
assert.equal(result, 5);
});
});

发现控制台会报错,待我研究一下。
avatar
avatar
用require也不行,确实,这个是直接运行在真实浏览器中的,什么require import什么的都是node的,可能不大好使,我突然想到刚才配置的是后问我要不要用Requirejs,懂了。

这感觉要配置webpack啊,我再查查。

  1. 还得再装 webpack babel babel-loader
    npm i webpack karma-webpack babel-loader @babel/core @babel/cli @babel/preset-env –save-dev
    装上webpack,需要再进行一些配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// my.conf.js
{
preprocessors: {
// 为选定脚本指定前处理器,这里配置所有的测试脚本需要经过webpack处理
"*.test.js": ["webpack"],
},

webpack: {
mode: "development",
// webpack配置,针对测试脚本打包的compilation配置,与项目文件打包不相关
// 也可以引入独立的配置文件
module: {
rules: [
{
test: /\.js$/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
},
},
},
],
},
},
}

经过webpack打包,babel之后,终于可以运行了。
可以看到打包的log
avatar
测试结果
avatar

为啥只能在浏览器控制台查看测试结果,而node后台没得,发现得启动的时候传一个参数 --log-level debug
karma start my.conf.js –log-level debug
avatar
有了

React支持

安装react 及 对应 babel-loader

npm i react react-dom @babel/preset-react –save-dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// my.conf.js
webpack: {
mode: "development",
// webpack配置,针对测试脚本打包的compilation配置,与项目文件打包不相关
// 也可以引入独立的配置文件
module: {
rules: [
{
test: /\.js$/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env", "@babel/preset-react"],
},
},
},
],
},
},
// demo.js
import React from "react";

class Container extends React.Component {
render() {
const { title } = this.props;
return <div className="title">{title}</div>;
}
}

export { Container };
// demo.test.js
import React from "react";
import ReactDOM from "react-dom";
import { Container } from "./demo";

it("third test", () => {
const root = document.createElement("div");
root.id = "app";
document.body.appendChild(root);
ReactDOM.render(
<Container title="hello world" />,
document.getElementById("app")
);
const reactComponent = document.querySelector(".title");
assert.exists(reactComponent);
assert.equal(reactComponent.innerText, "hello world");
});

avatar
测试成功!

测试覆盖率

安装 karma-coverage
npm i karma-coverage –save-dev

修改配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
{
preprocessors: {
// 为选定脚本指定前处理器,这里配置所有的测试脚本需要经过webpack处理
"*.test.js": ["webpack", "coverage"],
},
reporters: ["progress", "coverage"],
coverageReporter: {
type: "html",
// 第一文件夹
dir: "coverage",
// 第二文件夹 可以 string 可以function 根据不同浏览器 设置不同文件夹
// 将结果输出到: './coverage/chrome/'
subdir: function (browser) {
return browser.toLowerCase().split(/[ /-]/)[0];
},
// 下边的配置可以配置多种 type 的 报告
// reporters: [
// // reporters not supporting the `file` property
// { type: 'html', subdir: 'report-html' },
// { type: 'lcov', subdir: 'report-lcov' },
// // reporters supporting the `file` property, use `subdir` to directly
// // output them in the `dir` directory
// { type: 'cobertura', subdir: '.', file: 'cobertura.txt' },
// { type: 'lcovonly', subdir: '.', file: 'report-lcovonly.txt' },
// { type: 'teamcity', subdir: '.', file: 'teamcity.txt' },
// { type: 'text', subdir: '.', file: 'text.txt' },
// { type: 'text-summary', subdir: '.', file: 'text-summary.txt' },
// ]
},
}

启动测试
avatar
发现文件目录下多了文件夹,里边还有一堆前端资源文件 打开之后查看
avatar
棒棒,karma基本的使用咱们搞过一遍了,发现还是有不少东西的。

jest

下一篇再研究,溜了溜了。。。

参考

https://karma-runner.github.io/
https://github.com/dashnowords/Webpack4-Karma-Mocha-Chai-Demo/

×

纯属好玩

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

文章目录
  1. 1. 选型
  2. 2. karma
    1. 2.1. 官方推荐
    2. 2.2. 安装
    3. 2.3. 开整
    4. 2.4. React支持
    5. 2.5. 测试覆盖率
  3. 3. jest
  4. 4. 参考
,